package org.example;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

import java.util.*;

public class CSVDateParser extends FilesParser {
    private static String regexp = ".+\\.csv$";
    private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");

    private HashMap<String, LocalDate> stationDates;

    public CSVDateParser(String root) throws IOException, DataFormatException {
        super(root, regexp);
    }

    public static CSVDateParser parser(String root) throws IOException, DataFormatException {
        return new CSVDateParser(root);
    }

    protected void clear() {
        stationDates = new HashMap<>();
    }

    protected void parse(Reader reader) throws IOException, DataFormatException {
        CSVParser parser = CSVParser.parse(reader, CSVFormat.DEFAULT.withHeader());
        String stationName;
        LocalDate date;

        try {
            for (CSVRecord record : parser) {
                stationName = record.get("name");

                try {
                    date = LocalDate.parse(record.get("date"), dateFormatter);
                } catch (DateTimeParseException e) {
                    clear();
                    throw new DataFormatException("Wrong date format: " + record.get("date"));
                }

                //TODO Double dates
                //if (stationDates.get(stationName) != null) {
                //    System.out.println("Double dates of " + stationName);
                //}

                stationDates.put(stationName, date);
            }
        } finally {
            parser.close();
            reader.close();
        }
    }

    public Map<String, LocalDate> getStationDates() {
        return new TreeMap<>(stationDates);
    }

    public LocalDate getStationDate(String station) {
        return stationDates.get(station);
    }

    @Override
    public String toString() {
        StringJoiner stringJoiner = new StringJoiner(System.lineSeparator());

        for (Map.Entry<String, LocalDate> entry : getStationDates().entrySet()) {
            stringJoiner.add(entry.getKey() + "\t" + entry.getValue().format(dateFormatter));
        }

        return stringJoiner.toString();
    }
}
